package com.sgb.capital.view.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sgb.capital.R;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.TobepaidbillpaydetailsFragmentBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.PayDetailBean;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.Cards2Pop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.ui.activity.ApprovalActivity;
import com.sgb.capital.view.ui.activity.BillOrderDetailsActivity;
import com.sgb.capital.view.ui.activity.OrderErrorActivity;
import com.sgb.capital.view.ui.adapter.BalanceDetailsAdapter;
import com.sgb.capital.viewmodel.DetailsModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * 作者:张磊
 * 日期:2021/4/16 0016
 * 说明:支付信息
 */
public class BillPayDetailsFragment extends AppLazyFragment {

    private TobepaidbillpaydetailsFragmentBinding mBinding;
    private DetailsModel mModel;
    private List<Bean> mBeans = new ArrayList<>();
    private BalanceDetailsAdapter mAdapter;
    private BillOrderDetailsActivity mActivity;
    private TipPop mTipPop;
    private PayDetailBean mData;
    private Cards2Pop mCards2Pop;
    private Double mCode;
    private int mSwitchOn = -1;
    // private boolean isPay;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.tobepaidbillpaydetails_fragment, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mModel = new ViewModelProvider(this).get(DetailsModel.class);
        mBinding.rv.setLayoutManager(new LinearLayoutManager(Utils.getContext()));
        mTipPop = new TipPop(getActivity());
        mAdapter = new BalanceDetailsAdapter(null);
        mBinding.rv.setAdapter(mAdapter);
        mCards2Pop = new Cards2Pop(getActivity());

    }


    @Override
    public void initListener() {
        mTipPop.mTvSure.setOnClickListener(v -> {
            mTipPop.dismiss();
            Map map = new HashMap();
            map.put("operName", mActivity.mRealName);
            map.put("orderId", mActivity.mPayDetailBean.orderId);
            mModel.finish(mActivity, map);
        });
        mTipPop.mTvCancel.setOnClickListener(v -> {
            mTipPop.dismiss();
            if (mTipPop.mTip.contains("审批状态")) {
                mModel.getProcessInfo(mActivity);
                return;
            }
            if (mTipPop.mTip.contains("变化")) {
                mModel.getProcessInfo(mActivity);
                return;
            }
            if (mTipPop.mTip.contains("异常")) {
                mActivity.startActivity(new Intent(mActivity, OrderErrorActivity.class));
                return;
            }
            if (mCode == null) return;
        });
        mBinding.tvBtn.setOnClickListener(v -> {
            if (mBinding.tvBtn.getText().toString().contains("PC")) {
                return;
            }
            if (mActivity.mType == 1 && mBinding.tvBtn.getText().toString().contains("审批")) {
                mModel.validProcessBefore(mActivity, mActivity.mPayDetailBean.orderId, "1");
            } else if (mActivity.mType == 1) {
                mModel.getOrderPayStatus(mActivity, mActivity.mPayDetailBean.orderId);
             /*   isPay = true;
                mModel.getProcessInfo(mActivity);*/
            } else {
                mModel.getPayStatus(mActivity, mActivity.mPayDetailBean.orderId);
            }
        });
    }

    @Override
    public void initObserve() {
        mModel.mPayDetailBean.observe(this, payDetailBean -> {
            mActivity.mPayDetailBean = payDetailBean;
            mModel.getProcessInfo(mActivity);
        });

        mModel.mState2.observe(this, s -> {
            if (Utils.isEmpty(s)) {
                ApprovalActivity.start(mActivity, mActivity.mRealName, mActivity.mPayDetailBean.orderId, mActivity.mType);
            } else {
                if (s.equals("E80810007")) {
                    mTipPop.initStr("订单异常，无法付款", null, "知道了");
                    mTipPop.show();
                } else {
                    mTipPop.initStr("审批状态已发生变化，请刷新页面后再操作", null, "知道了");
                    mTipPop.show();
                }
            }
        });
        mModel.mProcessInfoBean.observe(this, processInfoBean -> {
            mActivity = (BillOrderDetailsActivity) getActivity();
            mSwitchOn = processInfoBean.switchOn;
          /*  if (isPay) {
                isPay = false;
                if (processInfoBean.switchOn == 1) {
                    mTipPop.initStr("审批状态已发生变化，请刷新页面后再操作", null, "知道了");
                    mTipPop.show();
                } else {
                    mModel.getOrderPayStatus(mActivity, mActivity.mPayDetailBean.orderId);
                }
            }*/

            if (processInfoBean.switchOn == 1) {
                mBinding.tvBtn.setText("发起审批");
            } else {
                mBinding.tvBtn.setText(mActivity.mType == 1 ? "余额支付" : "资金解冻");
            }
            mData = mActivity.mPayDetailBean;
            int type = mActivity.mType;
            mBinding.tvBtn.setVisibility(type > 2 ? View.GONE : View.VISIBLE);
            if (mActivity.mType <= 4) {
                mBinding.tvBtn.setText(type == 1 ? mSwitchOn == 1 && mActivity.mPayDetailBean.payApplyState == 0 ? "发起审批" :
                        mActivity.mPayDetailBean.payApplyState == 0 ? "余额支付" :
                                mActivity.mPayDetailBean.payApplyState == 1 ? "请前往PC端查看审批详情" :
                                        mActivity.mPayDetailBean.payApplyState == 2 ? "余额支付" : "发起审批" : "资金解冻");
                mBinding.tvBtn.setBackground(Utils.getResources().getDrawable(mActivity.mPayDetailBean.payApplyState == 1 ? R.drawable.button_false : R.drawable.button));
                mBinding.tvBtn.setTextColor(Utils.getColor(mActivity.mPayDetailBean.payApplyState == 1 ? R.color.color_FFC000 : R.color.white));
                if (mSwitchOn == 0 && mActivity.mPayDetailBean.payApplyState == 3) {
                    mBinding.tvBtn.setText("余额支付");
                }
            }
            if (mActivity.mType != 1) {
                mBinding.tvBtn.setVisibility(View.GONE);
            }
            list(mData, type);
        });
        mModel.mCode.observe(this, s -> {
            if (mActivity.mType == 1) {
                mCode = s;
                if (s == 6) {
                    mTipPop.initStr("温馨提示", " 订单异常,无法付款", null, "知道了");
                    mTipPop.show();
                } else if (s < 4) {
                    mCards2Pop.mBean = mActivity.mPayDetailBean;
                    mCards2Pop.show();
                } else {
                    mTipPop.initStr("温馨提示", mBinding.tvBtn.getText().toString().contains("审批") ? "审批状态已发生变化，请刷新页面后再操作" : " 订单状态已发生变化,请刷新页面后再进行操作", null, "知道了");
                    mTipPop.show();
                }
            } else {
                if (s == 7) {
                    mBinding.tvBtn.setVisibility(View.GONE);
                    mData.payState = 2;
                    list(mData, mActivity.mType);
                    Utils.sendMsg(Constants.EVENT_REFRESH_LIST, null);
                } else if (s == 1) {
                    mTipPop.initStr("是否确认解冻该订单资金？", "解冻后平台将解除订单资金担保，资金进入对方账户", "确定", "取消");
                    mTipPop.show();
                } else if (mActivity.mPayDetailBean.payStatus != s) {
                    mTipPop.initStr("温馨提示", " 订单状态已发生变化，请刷新页面后再进行操作", null, "知道了");
                    mTipPop.show();
                } else {
                    mTipPop.initStr("是否确认解冻该订单资金？", "解冻后平台将解除订单资金担保，资金进入对方账户", "确定", "取消");
                    mTipPop.show();
                }
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        mModel.getProcessInfo(mActivity);
    }

    private void list(PayDetailBean data, int type) {
        mBeans.clear();
        mBeans.add(new Bean(type > 4 ? "交易类型" : "订单类型", data.orderTypeName));
        if (type > 4) {
            mBeans.add(new Bean("转账单号", data.orderId));
        } else {
            mBeans.add(new Bean("订单号", data.paymentId));
        }
        if (type <= 4) {
            mBeans.add(new Bean("业务支付号", data.orderId));
        }
        if (type != 1 && type != 3) {
            mBeans.add(new Bean("交易流水号", data.flowNo));
        }
        mBeans.add(new Bean("付款方", Utils.isEmpty(data.payerCompanyName) ? "/" : data.payerCompanyName));
        if (type > 4) {
            mBeans.add(new Bean("收款方", Utils.isEmpty(data.payeeCompanyName) ? "/" : data.payeeCompanyName));
        } else {
            mBeans.add(new Bean("收款方", Utils.isEmpty(data.payeeName) ? "/" : data.payeeName));
        }
        mBeans.add(new Bean("订单金额", mActivity.mType > 4 ? Utils.getDecimalFormat(data.transferMoney) : Utils.getDecimalFormat(data.money)));
        if (type == 1) {
            mBeans.add(new Bean("申请人", Utils.isEmpty(data.payerCompanyName) ? data.contacts : data.contacts + "(" + data.payerCompanyName + ")"));
        }
        if (type == 2 && !data.payType.contains("余额")) {
            mBeans.add(new Bean("交易手续费", Utils.getDecimalFormat(data.fees)));
        }
        mBeans.add(new Bean("付款方式", mActivity.mType > 4 ? "在线付款" : data.method));
        //付款状态 0 审批中 1 审批通过 3 审批未通过 4 确认中 5 支付成功
        if (type == 2) {
            mBeans.add(new Bean("支付类型", data.payType));
            if (type == 2 && !data.payType.contains("余额")) {
                mBeans.add(new Bean("付款渠道", Utils.isEmpty(data.channel) ? "/" : data.channel));
                mBeans.add(new Bean("付款账户", Utils.isEmpty(data.account) ? "/" : data.account));
                mBeans.add(new Bean("付款账号", Utils.isEmpty(data.accountNumber) ? "/" : data.accountNumber));
            }
        }
        if (type == 5 || type == 6) {
            mBeans.add(new Bean("付款状态", data.payStatus == 0 ? "未付款" : data.payStatus == 1 ? "冻结中" : data.payStatus == 2 ? "支付成功" : "支付失败"));
        } else {
            //付款状态 0 审批中 1 审批通过 3 审批未通过 4 确认中 5 支付成功
            mBeans.add(new Bean("付款状态", data.state == 1 ? "未付款" : data.state == 4 ? "冻结中" : data.state == 5 ? "支付成功" : "支付异常"));
            if (mActivity.mType == 1) {
                mBeans.add(new Bean("审批状态", data.payApplyState == 2 ? "已通过" : data.payApplyState == 1 ? "审批中" : data.payApplyState == 0 ? "/" : "已拒绝"));
            }
        }
        //交易状态 0 未付款 1 冻结中 2 支付成功 3 支付失败
        if (type == 2) {
            mBeans.add(new Bean("资金状态", data.payState == 0 ? "未付款" : data.payState == 1 ? "冻结中" : data.payState == 2 ? "支付成功" : "支付失败"));
        }
        mBeans.add(new Bean(type != 1 ? "订单创建时间" : "创建时间", Utils.getTime(data.created)));
        if (type != 1) {
            mBeans.add(new Bean("付款时间", (type == 5 || type == 6) ? Utils.getTime(data.payTime) : type == 3 ? "/" : Utils.getTime(data.completionTime)));
        }
        if (type == 2) {
            mBeans.add(new Bean("交易备注", data.remark));
        }
        mAdapter.setNewInstance(mBeans);
        mAdapter.notifyDataSetChanged();
    }


    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_REFRESH_LIST:
                mBinding.tvBtn.setVisibility(View.GONE);
                mData.payState = 2;
                list(mData, mActivity.mType);
                break;
            case Constants
                    .EVENT_PAY_SUCCESS_PAY:
                mModel.getBillPayOrderDetails(mActivity, mActivity.mPayDetailBean.orderId);
                break;

        }
    }
}